package top.v5it.japi.ddd.core.web;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 存储请求头信息
 *
 * @author zhanpu
 * @date 2023/4/25
 */
@Slf4j
public enum HttpHeadFactory {

    /**
     * 实例
     */
    INSTANCE;

    /**
     * 请求头信息
     */
    private final static ThreadLocal<Map<String, String>> REQUEST_HEADER = new InheritableThreadLocal<>();

    /**
     * 响应头信息
     */
    private final static ThreadLocal<Map<String, String>> RESPONSE_HEADER = new InheritableThreadLocal<>();

    /**
     * 添加所有请求头
     *
     * @param param
     */
    void putRequestHeadAll(Map<String, String> param) {
        REQUEST_HEADER.set(param);
    }

    /**
     * 获取请求头
     *
     * @param name
     * @return
     */
    public Optional<String> getRequestHeader(String name) {
        return Optional.ofNullable(REQUEST_HEADER.get()).map(header -> header.get(name));
    }

    /**
     * 获取所有请求头
     *
     * @return
     */
    public Optional<Map<String, String>> getRequestHeaderAll() {
        return Optional.ofNullable(REQUEST_HEADER.get());
    }

    /**
     * 添加所有响应头
     *
     * @param param
     */
    public void putResponseHeadAll(Map<String, String> param) {
        RESPONSE_HEADER.set(param);
    }

    /**
     * 添加请求头
     *
     * @param key
     * @param name
     */
    public void putResponseHead(String key, String name) {
        final Map<String, String> header = Optional.ofNullable(RESPONSE_HEADER.get()).orElseGet(HashMap::new);
        header.put(key, name);
        RESPONSE_HEADER.set(header);
    }

    /**
     * 获取所有响应头
     *
     * @return
     */
    Optional<Map<String, String>> getResponseHeaderAll() {
        return Optional.ofNullable(RESPONSE_HEADER.get());
    }

    /**
     * 清理资源
     */
    void remove() {
        log.info("清理头信息");
        REQUEST_HEADER.remove();
        RESPONSE_HEADER.remove();
    }
}
